package cn.tedu.blog.server.repo.impl;

import cn.tedu.blog.server.pojo.vo.CategoryListVO;
import cn.tedu.blog.server.pojo.vo.LinkListItemVO;
import cn.tedu.blog.server.repo.ILinkRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Repository
public class LinkRepository implements ILinkRepository {

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;
    @Override
    public boolean isExpired(String key) {
        Long expiredTime= redisTemplate.getExpire(key);
        log.debug("密钥有效时间：{}",expiredTime);
        if(expiredTime==-2){
            return true;
        }
        return false;
    }

    @Override
    public void putList(List<LinkListItemVO> list, String key) {
        for (LinkListItemVO categoryListVO : list) {
            redisTemplate.opsForList().rightPush(key, categoryListVO);
        }
        switch (key){
            case KEY_Link_LIST:
                redisTemplate.expire(key,1L, TimeUnit.DAYS);
                break;
        }
    }

    @Override
    public List<LinkListItemVO> getList(String key) {
        log.debug("即将从Redis中读取分类列表数据……");
        List<Serializable> list = redisTemplate.opsForList().range(key, 0, -1);
        List<LinkListItemVO> linkList = new ArrayList<>();
        for (Serializable serializable : list) {
            linkList.add((LinkListItemVO) serializable);
            log.debug("从Redis中读取到的友链列表：{}",linkList);
        }
        return linkList ;
    }
}
